package com.ccnode.codegenerator.taikaoback.security.filter;

import com.ccnode.codegenerator.taikaoback.entity.LoginUser;
import com.ccnode.codegenerator.taikaoback.security.jwt.JwtUtil;
import com.ccnode.codegenerator.taikaoback.service.TokenService;
import com.ccnode.codegenerator.taikaoback.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * JWT认证过滤器
 */
@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            // 如果没有token，直接放行，让Spring Security处理
            filterChain.doFilter(request, response);
            return;
        }

        // 解析token
        token = token.substring(7);
        
        // 验证token有效性
        try {
            if (!tokenService.validateToken(token)) {
                filterChain.doFilter(request, response);
                return;
            }
        } catch (Exception e) {
            // 如果验证过程中出现异常，直接放行让后续流程处理
            filterChain.doFilter(request, response);
            return;
        }

        // 从token中获取用户名
        String username = jwtUtil.getUnameFromToken(token);
        if (Objects.isNull(username)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 将用户信息存入UserContext
        UserContext.set("username", username);

        // 构建UsernamePasswordAuthenticationToken
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        UsernamePasswordAuthenticationToken authenticationToken = 
                new UsernamePasswordAuthenticationToken(loginUser, null, null);

        // 存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
        
        // 清理UserContext
        UserContext.remove();
    }
}